package com.fancon.rage.comic.vn.activity;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import net.arnx.jsonic.JSONException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;

import com.fancon.android.common.FanconProgressBar;
import com.fancon.android.multithread.RequestUI;
import com.fancon.rage.comic.vn.R;
import com.fancon.rage.comic.vn.apiservice.RageApiService;
import com.fancon.rage.comic.vn.entity.Photo;
import com.fancon.rage.comic.vn.gui.ComicEnView;
import com.fancon.rage.comic.vn.gui.ComicVnView;
import com.fancon.rage.comic.vn.gui.IRageTopControl;
import com.fancon.rage.comic.vn.gui.IRefreshable;
import com.fancon.rage.comic.vn.gui.TopControlView;
import com.fancon.rage.comic.vn.local.db.RageSqlHelper;
import com.fancon.rage.comic.vn.local.entity.FootPrint;
import com.handmark.pulltorefresh.library.PullToRefreshListView;

/**
 * 
 * @author binhbt 2012 Main activity
 */
public class RageVietActivity extends RageBaseActivity implements
		IRageTopControl, IRefreshable {
	/** Called when the activity is first created. */
	private ComicVnView vnView;
	private ComicEnView enView;
	private TopControlView controlView;
	private ArrayList<String> footPrint = new ArrayList<String>();
	private RageSqlHelper sqlHelper;
	private Cursor cr;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rage_list);
		vnView = (ComicVnView) findViewById(R.id.vn_view);
		enView = (ComicEnView) findViewById(R.id.en_view);
		controlView = (TopControlView) findViewById(R.id.top_control);
		// init with no data
		vnView.loadPhotos(null);
		getLogFootPrint();
		loadApi();
	}

	public void loadApi() {
		RageRequest allRageRequest = new RageRequest("ragevn", this);
		getGlobalState().getRequestQueue().addRequest(allRageRequest);
	}

	private void getLogFootPrint() {
		FootPrintRequest fp = new FootPrintRequest("ragefp", this);
		getGlobalState().getRequestQueue().addRequest(fp);
	}

	@Override
	public void doVn() {
		// TODO Auto-generated method stub
		vnView.setVisibility(View.VISIBLE);
		enView.setVisibility(View.GONE);
	}

	private void loadData(ArrayList<Photo> photos) {
		switch (controlView.getCurrentMode()) {
		case TopControlView.VN_MODE:
			vnView.loadPhotos(photos);
			break;
		case TopControlView.EN_MODE:
			enView.loadPhotos(photos);
			break;
		default:
			break;
		}
	}

	@Override
	public void doRefresh(PullToRefreshListView pullList) {
		loadApi();
		pullList.onRefreshComplete();
	}

	@Override
	public void doEn() {
		// TODO Auto-generated method stub
		enView.setVisibility(View.VISIBLE);
		vnView.setVisibility(View.GONE);
		if (enView.getIsFrist()) {
			enView.loadPhotos(null);
			loadApi();
			enView.setIsFrist(false);
		}
	}

	public void setFootPrint(ArrayList<String> footPrint) {
		this.footPrint = footPrint;
	}

	public ArrayList<String> getFootPrint() {
		return footPrint;
	}

	class RageRequest extends RequestUI {
		private ArrayList<Photo> photos;
		private FanconProgressBar progress;

		@SuppressWarnings("static-access")
		public RageRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			progress = FanconProgressBar.show(activity,
					activity.getString(R.string.loading));
		}

		@Override
		public void execute() {
			// TODO Auto-generated method stub
			RageApiService apiService = new RageApiService(
					getApplicationContext());
			try {
				photos = apiService.getAllComics(controlView.getCurrentMode());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (org.json.JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			loadData(photos);
			progress.dismiss();
		}

	}

	class FootPrintRequest extends RequestUI {

		public FootPrintRequest(Object key, Activity activity) {
			super(key, activity);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			getAllFootPrint();
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			//cr.close();
			//sqlHelper.close();
		}
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		cr.close();
		sqlHelper.close();
		super.onDestroy();
	}

	private void getAllFootPrint() {
		sqlHelper = new RageSqlHelper(this);
		sqlHelper.createDatabase();
		sqlHelper.openDataBase();
		cr = sqlHelper.getFootPrint();
		if (cr != null) {
			footPrint = new ArrayList<String>();
			startManagingCursor(cr);
			while (cr.moveToNext()) {
				String photoId = cr.getString(cr
						.getColumnIndex(FootPrint.PHOTOID));
				if (photoId != null) {
					footPrint.add(photoId);
				}
			}
		}

	}
	@Override
	public void onBackPressed() {
	    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setMessage("Are you sure you want to exit?")
	           .setCancelable(false)
	           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	            	   RageVietActivity.this.finish();
	               }
	           })
	           .setNegativeButton("No", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    dialog.cancel();
	               }
	           });
	    AlertDialog alert = builder.create();
	    alert.show();

	}

}